package com.xtwy.service;

import com.xtwy.entity.Role;
import com.xtwy.entity.User;
import com.xtwy.mapper.UserMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * @作 者: 侯建军
 * @日 期: 2018/7/28 18:13
 * @描 述: 用户登录
 * @公 司：山西迅腾伟业
 */
@Service
public class MyUserDetails implements UserDetailsService {

    private static final Logger logger = LogManager.getLogger(MyUserDetails.class);

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /**
         * 账号查询
         */
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        User user=userMapper.selectOneByExample(example);
        System.out.print(user);
        if(user==null){
            throw  new UsernameNotFoundException("用户不存在");
        }
        System.out.print("--------------------------------------");
        //简单验证
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //添加角色,角色值要加 ROLE_前缀
        authorities.add(new SimpleGrantedAuthority("ROLE_admin"));
        authorities.add(new SimpleGrantedAuthority("ROLE_user"));
//        for (Role roles:sysUser.getRoles()){
//
//            authorities.add(new SimpleGrantedAuthority(roles.getRname()));
//            System.out.print(roles.getRname());
//        }
        //通过数据用户名密码进行验证
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),user.getPassword(),authorities);
    }
}
